var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const { createServer } = require("http");   // 1、新增的
var cors = require('cors');
// var expressJWT = require('express-jwt')
var { fzliaotianModel, appliaotianModel } = require('./model/model')


var lxrRouter = require('./routes/lxr');
var sdk = require('./routes/sdk');

var lwlRouter = require('./routes/lwl');

var jjt = require('./routes/jjt');

var lxjRouter = require('./routes/lxj');

var usersRouter = require('./routes/users');



var app = express();
app.use(cors())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


// 2、新增的
const httpServer = createServer();
// 3、导入socket.io
const io = require("socket.io")(httpServer, {
  cors: {
    origin: "*",
  }
});


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use("/upload",express.static(path.join(__dirname, 'upload')));



app.use('/', lwlRouter);
app.use('/sdk', sdk);
app.use('/lxr', lxrRouter);
app.use('/lxj', lxjRouter);
app.use('/jjt', jjt);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});


// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// 4、搭建socket.io服务器
io.on('connection', (socket) => {
  console.log('有人连接--A');

  //接收前段发送的数据
  socket.on('send', async (data) => {//data是发送过来的数据
    // fzliaotianModel.create(JSON.parse(data))
    console.log('前端的数据:',data);
    let ls = JSON.parse(data)
    // console.log('我想看的东西:', socket);

    // 与房主的聊天
    let fdata = await fzliaotianModel.find(
      {
        $or: [
          { mename: ls.mename, youname: ls.youname },
          { youname: ls.mename, mename: ls.youname }
        ]
      }
    )
    console.log(fdata);
    socket.broadcast.emit('fdata', fdata);  //广播给除了自己的其他客户端

    // 与客服的聊天
    let adata = await appliaotianModel.find(
      {
        $or: [
          { meaname: ls.meaname, youaname: ls.youaname },
          { youaname: ls.meaname, meaname: ls.youaname }
        ]
      }
    )
    console.log(adata);
    socket.broadcast.emit('adata', adata);  //广播给除了自己的其他客户端
  });

});

httpServer.listen(4000, () => {
  console.log('服务器启动成功');
})


module.exports = app;
